<script setup lang="ts">
import { Refresh, Search, Timer } from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { FriendService, UserApplyCriteria, UserApplyVo } from '/@/api/openapi'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserFriendStore, useUserStore } from '/@/store'
import { storeToRefs } from 'pinia'

const tableRef = ref()
const searchParams = ref<UserApplyCriteria>({
  pageNum: 1,
  pageSize: 10,
})
const total = ref(0)
const store = useUserStore()
const userFriendStore = useUserFriendStore()
const { userApply } = storeToRefs(userFriendStore)
const loading = ref(false)
const searchKeyword = ref('')

const handleCurrentChange = (val: number) => {
  searchParams.value.pageNum = val
  loadData()
}

const loadData = async () => {
  loading.value = true
  try {
    await userFriendStore.updateUserApply(searchParams.value)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  searchParams.value.pageNum = 1
  loadData()
}

onMounted(() => {
  if (store.isSign) {
    loadData()
  }
})

// 通过好友申请
const handleAccess = async (data: UserApplyVo) => {
  if (data.id === undefined) return

  try {
    await ElMessageBox.confirm(
      `确定要通过 ${data.username} 的好友申请吗？`,
      '通过好友申请',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
      },
    )

    const res = await FriendService.accessApply(data.id)
    ElMessage({
      type: 'success',
      message: res.message,
    })
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: error as string,
      })
    }
  }
}

// 拒绝好友申请
const handleReject = async (data: UserApplyVo) => {
  if (data.id === undefined) return

  try {
    await ElMessageBox.confirm(
      `确定要拒绝 ${data.username} 的好友申请吗？`,
      '拒绝好友申请',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    const res = await FriendService.deleteUserApply(data.id)
    ElMessage({
      type: 'success',
      message: res.message,
    })
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage({
        type: 'error',
        message: error as string,
      })
    }
  }
}

const getStatusType = (status: number) => {
  switch (status) {
    case 1:
      return 'info'
    case 2:
      return 'success'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '待处理'
    case 2:
      return '已通过'
    case 3:
      return '已拒绝'
    default:
      return '未知状态'
  }
}
</script>

<template>
  <div class="apply-list-container">
    <div class="header">
      <h2 class="title">好友申请</h2>
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索申请人"
          class="search-input"
          :prefix-icon="Search"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>

    <div class="table-container">
      <el-button
        @click="loadData"
        class="refresh-btn"
        :loading="loading"
        type="primary"
        plain
      >
        <el-icon><Refresh /></el-icon>
        刷新列表
      </el-button>

      <el-table
        :ref="tableRef"
        :data="userApply.records"
        style="width: 100%"
        v-loading="loading"
        :empty-text="'暂无好友申请'"
        border
        stripe
      >
        <el-table-column prop="username" label="申请人" min-width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="row.avatar || ''" />
              <span class="username">{{ row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="applyInfo"
          label="申请理由"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="status" label="状态" min-width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              <el-icon><Timer /></el-icon>
              <span class="status-text">{{ getStatusText(row.status) }}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row }">
            <el-button
              type="success"
              link
              size="small"
              @click="handleAccess(row)"
              :disabled="row.status !== 1"
            >
              通过
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleReject(row)"
              :disabled="row.status !== 1"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="userApply.total"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.apply-list-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.table-container {
  margin-top: 20px;
}

.refresh-btn {
  margin-bottom: 16px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: 500;
  color: #303133;
}

.status-text {
  margin-left: 4px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media screen and (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 16px;
  }

  .search-box {
    width: 100%;
  }

  .search-input {
    width: 100%;
  }
}
</style>
